﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Xml;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace DWH.Configuration
{
    public class RDConfigurationHandler : IConfigurationSectionHandler
    {
        private const string KEY_CONFIG_SOURCE = "rdTaskFiles";
        private const string KEY_NAME = "TaskName";
        private const string KEY_ENABLE = "Enable";
        private const string KEY_ASSEMBLY_FILE = "AssemblyFile";
        private const string KEY_TYPE_NAME = "TypeName";
        private const string KEY_EXTEND_DATA = "ExtendData";


        public object Create(object parent, object configContext, XmlNode section)
        {
            if (section.Attributes[KEY_CONFIG_SOURCE] != null)
            {
                string[] configFiles = section.Attributes[KEY_CONFIG_SOURCE].Value.Split(';');

                List<RDTaskConfiguration> tasks = new List<RDTaskConfiguration>();
                XmlDocument doc = null;
                string configFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                foreach (string configFile in configFiles)
                {
                    if (!String.IsNullOrEmpty(configFile) && File.Exists(Path.Combine(configFolder,configFile)))
                    {
                        doc = new XmlDocument();
                        doc.LoadXml(File.ReadAllText(Path.Combine(configFolder, configFile)));
                        tasks.AddRange(LoadFromXmlNode(doc.DocumentElement));
                    }
                }

                return tasks;
            }
            else
            {
                return LoadFromXmlNode(section);
            }
        }

        public static List<RDTaskConfiguration> LoadFromXmlNode(XmlNode rdConfigNode)
        {
            List<RDTaskConfiguration> rds = new List<RDTaskConfiguration>();
            RDTaskConfiguration config = null;

            foreach (XmlNode node in rdConfigNode)
            {
                if (node.NodeType == XmlNodeType.Comment)
                {
                    continue;
                }
                config = new RDTaskConfiguration();

                config.TaskName = node.Attributes[KEY_NAME].Value;
                config.Enable = bool.Parse(node.Attributes[KEY_ENABLE].Value);
                config.AssemblyFile = node.Attributes[KEY_ASSEMBLY_FILE].Value;
                config.TypeName = node.Attributes[KEY_TYPE_NAME].Value;

                foreach (XmlNode extendData in node.ChildNodes)
                {
                    if (extendData.Name == KEY_EXTEND_DATA)
                    {
                        foreach (XmlNode data in extendData)
                        {
                            config.ExtendData.Add(data.Name, data.InnerText);
                        }
                    }
                }

                rds.Add(config);
            }

            return rds;
        }

        public static List<RDTaskConfiguration> LoadFromXlsFile(string filePath)
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            Excel.Range range;

            string str;
            int rCnt = 0;
            int cCnt = 0;

            xlApp = new Excel.Application();//.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Open(filePath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            range = xlWorkSheet.UsedRange;

            for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
            {
                for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
                {
                    str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
                }
            }

            xlWorkBook.Close(true, null, null);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            return null;
        }

        private static void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
            }
            finally
            {
                GC.Collect();
            }
        }


    }
}
